from __future__ import unicode_literals
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

def upload_location(instance, filename):
	return "%s/%s" %(instance.id, filename)

class Post(models.Model):
	user = models.ForeignKey(settings.AUTH_USER_MODEL)
	name = models.CharField(max_length=128)
	price = models.FloatField()

	car = '校园代步'
	phone = '手机'
	computer = '电脑'
	parts = '数码配件'
	camera = '数码产品'
	electrical = '小电器'
	book = '图书教材'
	other = '其他'

	STUFF_CATEGORY_CHOICES = (
		(car, '校园代步'),
		(phone, '手机'),
		(computer, '电脑'),
		(parts, '数码配件'),
		(camera, '数码产品'),
		(electrical, '小电器'),
		(book, '图书教材'),
		(other, '其他'),
	)

	category = models.CharField(max_length=128,
								 choices=STUFF_CATEGORY_CHOICES,
								 default=book)
	slug = models.SlugField(unique=True)
	image = models.ImageField(upload_to=upload_location,
								width_field="width_field",
								height_field="height_field")
	height_field = models.IntegerField(default=250)
	width_field = models.IntegerField(default=286)
	updated = models.DateTimeField(auto_now=True, auto_now_add=False)
	timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
	description = models.TextField()

	class Meta:
		ordering = ['-timestamp']

	def __str__(self):
		return self.name

def create_slug(instance, new_slug=None):
	slug = slugify(instance.name)
	if new_slug is not None:
		slug = new_slug
	qs = Post.objects.filter(slug=slug).order_by("-id")
	exists = qs.exists()
	if exists:
		new_slug = "%s-%s" %(slug, qs.first().id)
		return create_slug(instance, new_slug=new_slug)
	return slug


def pre_save_post_receiver(sender, instance, *args, **kwargs):
	if not instance.slug:
		instance.slug = create_slug(instance)



pre_save.connect(pre_save_post_receiver, sender=Post)

		

